﻿import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail

from views_common import *
import models

import smth_viewpoint as smth

# ##########################################################################################################################
# /vp/boards/
def boards(request):
    xml = '''<?xml version="1.0" encoding="UTF-8"?>
<boards>
    <board board_name="NewExpress" board_id="582" order="1" description="水木特快"></board>
    <board board_name="Love" board_id="73" order="2" description="谈情说爱"></board>
    <board board_name="FamilyLife" board_id="9" order="3" description="家庭生活"></board>
    <board board_name="MyPhoto" board_id="874" order="4" description="个人Show"></board>
    <board board_name="Joke" board_id="63" order="5" description="笑话"></board>
    <board board_name="Apple" board_id="719" order="6" description="苹果"></board>
    <board board_name="NewSoftware" board_id="99" order="7" description="新软"></board>
    <board board_name="ITExpress" board_id="26" order="8" description="IT特快"></board>
    <board board_name="MyWallet" board_id="574" order="9" description="个人理财"></board>
    <board board_name="CreditCard" board_id="1097" order="10" description="信用卡理财"></board>
    <board board_name="Age" board_id="953" order="11" description="大龄男女"></board>
    <board board_name="Movie" board_id="92" order="12" description="电影"></board>
    <board board_name="OMTV" board_id="448" order="13" description="欧美电视"></board>
    <board board_name="RealEstate" board_id="309" order="14" description="房地产论坛"></board>
    <board board_name="RealEstate_review" board_id="1112" order="15" description="房产观澜"></board>
    <board board_name="WorkLife" board_id="383" order="16" description="职业生涯"></board>
    <board board_name="PrisonBreak" board_id="904" order="17" description="越狱"></board>
    <board board_name="GuoJiXue" board_id="540" order="18" description="国计学"></board>
    <board board_name="EconForum" board_id="225" order="19" description="经济论坛"></board>
</boards>'''

    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /vp/boardsinfo1/
def boardsinfo1(request):
    items = smth.crawlingBoardsInfo()
    output = '<pre>'
    for item in items:
        output += item[0]+','+item[1]+','+item[2].replace(",", "").strip()+','+item[3]+','+item[4]+'\n'
        board = models.Board(board_id=int(item[0]), board_name=unicode(item[1], 'utf-8', 'ignore'), board_desc=unicode(item[2], 'utf-8', 'ignore'), board_class=int(item[3]), board_type=int(item[4]))
        board.put()
    output += '<pre>'
    response = HttpResponse(output)
    #response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /vp/crawlingboards/
def crawlingboards(request):
    try:
        class_id = request.GET.get('class_id', "0")
        user = getUser()
        logging.info(user.email())
        
        if(user.email()=='ldmiao@gmail.com'):
            
            boards = models.Board.all().fetch(5)
            if(len(boards)>0):
                return HttpResponseRedirect('/vp/deleteboards/')
            
            output = '''
            <html>
                <head>
                    <script src="/media/scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
                    <script type="text/javascript">
                        //crawling boards
                        function processClass(class_id){
                            $.get("/vp/boardsinfo/?class_id="+class_id,
                                function(data){
                                    if(data && data!=""){
                                        $('body').append('<div> crawling boards:'+data+'</div><br/>');
                                        var mySplitResult = data.split(",");
                                        for(i = 0; i < mySplitResult.length; i++){
                                            //alert(mySplitResult[i]+"");
                                            processClass(mySplitResult[i]+"");
                                            //sleep(2000);
                                        }
                                    }
                                }
                            );
                        }
                        processClass('0');
                    </script>
                </head>
                <body>
                
                </body>
            </html>
            '''
            
            response = HttpResponse(output)
            return response
        else:
            login_text, login_url = getLoginAndUrl(request)
            output = '''<a href="%s">%s</a>'''%(login_url, login_text)
            return HttpResponse(output)
    except:
        return HttpResponse("")
# ##########################################################################################################################
# /vp/deleteboards/
def deleteboards(request):
    try:
        count = request.GET.get('count', None)
        
        user = getUser()
        logging.info(user.email())
        if(user.email()=='ldmiao@gmail.com'):
            output = ''
            if count:
                boards = models.Board.all().fetch(100)
                
                if(len(boards)>0):
                    output = str(len(boards))
                
                db.delete(boards)
                
            else:
                output = '''
                <html>
                    <head>
                        <script src="/media/scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
                        <script type="text/javascript">
                            
                            //delete boards
                            function deleteBoards(){
                                $.get("/vp/deleteboards/?count=100",
                                    function(data){
                                        if(data && data!=""){
                                            $('body').append('<div>delete boards:'+data+'</div><br/>');
                                            deleteBoards();
                                        }else{
                                            $('body').append('<div>delete boards: done!</div><br/><a href="/vp/crawlingboards/">crawling boards</a><br/>');
                                            window.location.href='/vp/crawlingboards/';
                                        }
                                    }
                                );
                            }
                            
                            deleteBoards();
                        </script>
                    </head>
                    <body>
                    
                    </body>
                </html>
                '''
                
            response = HttpResponse(output)
            return response
            
        else:
            login_text, login_url = getLoginAndUrl(request)
            output = '''<a href="%s">%s</a>'''%(login_url, login_text)
            return HttpResponse(output)
    except:
        return HttpResponse("")
# ##########################################################################################################################
# /vp/deleteposts/
def deleteposts(request):
    output = ""
    user = getUser()
    if(user and user.email()=='ldmiao@gmail.com'):
        posts = models.Post.all().fetch(100)
                    
        if(len(posts)>0):
            output = str(len(posts))
            output += "<script>window.location.href='/vp/deleteposts/';</script>"
        db.delete(posts)
    else:
        login_text, login_url = getLoginAndUrl(request)
        output = '''<a href="%s">%s</a>'''%(login_url, login_text)
    return HttpResponse(output)
# ##########################################################################################################################
# /vp/boardsinfo/
def boardsinfo(request):
    try:
        class_id = request.GET.get('class_id', "0")
        user = getUser()
        logging.info(user.email())
        if(user.email()=='ldmiao@gmail.com'):
            items = smth.getBoardsInfo(class_id)
            output = ''
            
            for item in items:
                if(item[4]=='0'):
                    output += item[0]+','
                board_name = unicode(item[1].strip(), 'utf-8', 'ignore')
                board = models.Board(board_id=int(item[0].strip()), board_name=board_name, board_name_lowercase=board_name.lower(), board_desc=unicode(item[2].strip(), 'utf-8', 'ignore'), board_class=int(item[3].strip()), board_type=int(item[4].strip()))
                board.put()
                
            output = output[0: len(output)-1]
            logging.info(output)
            
            response = HttpResponse(output)
            return response
        else:
            login_text, login_url = getLoginAndUrl(request)
            output = '''<a href="%s">%s</a>'''%(login_url, login_text)
            return HttpResponse(output)
    except:
        return HttpResponse("")
    
# ##########################################################################################################################
# /vp/boardinfo/
def boardinfo(request):
    try:
        board_name = request.GET.get('board_name', "NewExpress")
        
        board = db.GqlQuery('''SELECT * FROM Board WHERE board_name_lowercase=:1 and board_type=1''', board_name.strip().lower()).get()
        
        board_id = ''
        description = ''
        page_num_real= ''
        if board:
            board_name = board.board_name
            board_id = str(board.board_id)
            description = board.board_desc
            logging.info('board info retrived from datastore!')
        else:
            board_name, board_id, description, page_num_real = smth.getBoardInfoThroughSmth(board_name)
            logging.info('board info retrived from newsmth!')
        
        xml =  '''<?xml version="1.0"?>'''
        xml += '''<board board_name="'''+board_name+'''" description="'''+description+'''" page_num="'''+page_num_real+'''" board_id="'''+board_id+'''" order="1"/>'''

        response = HttpResponse(xml)
        response['Content-Type'] = 'text/xml'
        return response
    except:
        return HttpResponse("")
    
# ##########################################################################################################################
# /vp/threads/
def threads(request):
    try:
        board_name = request.GET.get('board_name', "NewExpress")
        board_id = int(request.GET.get('board_id', '0'))
        #page_num = 0 means as the last page
        page_num = int(request.GET.get('page_num', '0'))
        
        board_id, threads, page_num_real = smth.getThreadList(board_name, page_num)
        
        xml =  '''<?xml version="1.0" encoding="UTF-8"?>'''
        xml += '''<threads board_name="'''+board_name+'''" board_id="'''+board_id+'''" page_num="'''+page_num_real+'''">'''
        for thread in threads:
            #0:thread_id, 1:title, 2:word_count, 3:thread_url
            xml += '''<thread title="'''+thread[1]+'''" thread_id="'''+thread[0]+'''" user="" date=""></thread>'''
        xml += '''</threads>'''

        response = HttpResponse(xml)
        response['Content-Type'] = 'text/xml'
        return response
    except:
        return HttpResponse("")

# ##########################################################################################################################
# /vp/posts/
def posts(request):
    try:
        board_name = request.GET.get('board_name', "NewExpress")
        board_id = int(request.GET.get('board_id', '0'))
        #page_num = 0 means as the last page
        page_num = int(request.GET.get('page_num', '0'))
        
        logging.info(page_num)
        
        board_id, posts, page_num_real = smth.getPostList(board_name, page_num)
        
        xml =  '''<?xml version="1.0"?>'''
        xml += '''<posts board_name="'''+board_name+'''" page_num="'''+page_num_real+'''" board_id="'''+board_id+'''">'''
        for post in posts:
            #0:post_id, 1:thread_id, 2:author, 3:tag, 4:post_time, 5:title, 6:word_count
            xml += '''<post title="'''+post.title+'''" thread_id="'''+str(post.thread_id)+'''" post_id="'''+str(post.post_id)+'''" user="'''+post.author+'''" date="'''+str(post.post_time)+'''" word_count="'''+str(post.word_count)+'''" tag="'''+post.tag+'''"><![CDATA[]]></post>'''
        xml += '''</posts>'''

        response = HttpResponse(xml)
        response['Content-Type'] = 'text/xml'
        return response
    except:
        return HttpResponse("")

    
# ##########################################################################################################################
# /vp/post/
def post(request):
    #try:
        board_name = request.GET.get('board_name', "NewExpress")
        board_id = request.GET.get("board_id", None)
        #thread_id = request.GET.get("thread_id", "0")
        post_id = request.GET.get("post_id", None)
        post_type = request.GET.get("post_type", None)
        logging.info(post_type)
        
        config = getPostConifg(request)
        #logging.info(config)
        
        xml = '''<?xml version="1.0" encoding="UTF-8"?>'''
        
        if board_id and post_id:
            post_id, thread_id, post_title, postContent = getPostContent(board_id, post_id, post_type, config)
            xml += '''<post board_name="'''+board_name+'''" board_id="'''+str(board_id)+'''" thread_id="'''+str(thread_id)+'''" post_id="'''+str(post_id)+'''" title="'''+post_title+'''"><![CDATA['''+postContent+''']]></post>'''

        response = HttpResponse(xml)
        response['Content-Type'] = 'text/xml'
        return response
    #except:
    #    return HttpResponse("")

# ##########################################################################################################################
def getMaxIdForCss():
    query = db.GqlQuery("SELECT * FROM Style ORDER BY id DESC")
    style = query.get()
    if style:
        return style.id
    return 0
        
# ##########################################################################################################################
# /vp/css/
def css(request):
    try:
        html = u"""
        <html>
            <head>
                <title>CSS Setting</title>
                <script type="text/javascript">
                    function showResult(){
                        var styleTag = document.getElementsByTagName('style');
                        if (styleTag.length > 0) {
                            //styleTag[0].innerHTML = document.getElementById('css_textarea').value;
                            var style_str = document.getElementById('css_textarea').value;
                            while(styleTag[0].firstChild){
                                styleTag[0].removeChild(styleTag[0].firstChild);
                            }
                            styleTag[0].appendChild(document.createTextNode(style_str));
                        }
                    }
                </script>
                <style>%s</style>
            </head>
            <body>%s%s</body>
        </html>
        """
        head_css = u"\n.head {font-size:14px;}\n.title {}\n.sender {}\n.date {}\n.ip {}\n.attr {color:#CAFF70;}\n.val {color:gold;}\n.reference {font-size:14px;margin-left:8px;border-left:thin solid gray;color:gray;}\n.attachment {font-size:14px;}\n.signature {font-size:14px;margin-right:2px;color:#CC66CC;}"
        css = u"\nbody{ background-color:#222; COLOR:#CCCCCC;}\n.post {font-family:Georgia; font-size:18px; -webkit-text-size-adjust:none; line-height:1.5;border-top: 1px solid #CCCCCC;}\n%s\n"%(head_css)
        
        body = u'''
        <div style="width:300px;height:440px;">
            <div class="post">
                <div class="head">
                    <div class="title"><span class="attr">标题:</span><span class="val">标题标题标题标题</span></div>
                    <div class="sender"><span class="attr">作者:</span><span class="val">ldmiao (阿苗)</span></div>
                    <div class="date"><span class="attr">时间:</span><span class="val">2009-03-09 Mon 00:17:02</span></div>
                </div>
                <div class="content">帖子正文帖子正文帖子正文帖子正文<br/>帖子正文帖子正文帖子正文<br/>帖子正文帖子正文帖子正文<br/>帖子正文帖子正文帖子正文</div>
                <div class="reference">引用引用引用引用引用引用引用引用<br/>引用引用引用引用引用引用引用引用</div>
                <div class="attachment">附件.jpg<br/><!--img src="http://ipsmth.googlecode.com/svn/trunk/screenshots/图标.png"/--></div>
                <div class="signature">签名档签名档签名档<br/>签名档签名档签名档签名档</div>
            </div>
        </div>
        '''
        login_text, login_url = getLoginAndUrl(request)
        login_text = unicode(login_text, 'utf-8')
        
        login_html = u"<a href='%s'>%s</a>"%(login_url, login_text)
        
        body_new = u"""
        CSS:<br/>
        <div style="width:300px; height:420px;border:thin solid #FFFFFF;">
            <form action='/vp/css/?action=update' method="POST">
                %s
                <textarea onblur='showResult()' id='css_textarea' name='content' style='width:300px; height:380px;font-family:Georgia;'>%s</textarea><br/>
                <input type='button' value='Refresh' onclick='showResult()'/><input type='submit' value='Submit'/>
            </form>
        </div>
        """
        user=getUser()
        
        action = request.GET.get('action', None)
        if action=="add":
            body_new = body_new%("", css)
            html = html%(css, body, body_new)
            return HttpResponse(html)
        elif action=="edit":
            id = request.GET.get('id', None)
            id_html = ""
            if id is not None:
                #style = models.Style.all().filter("id=", int(id)).get()
                query = db.GqlQuery("SELECT * FROM Style WHERE id=:1", int(id))
                style = query.get()
                logging.info(style)
                if style:
                    css = style.content
                    id_html = u"<input type='hidden' name='id' value='%s'/>"%(id)
            
            body_new = body_new%(id_html, css)
            html = html%(css, body, body_new)
            return HttpResponse(html)
        elif action=="update":
            id = request.POST.get('id', None)
            content = request.POST.get('content', None)
            
            if id is None:
                id = getMaxIdForCss()+1
            else:
                id = int(id)
            
            style = None
            if content is not None:
                if id is not None:
                    #style = models.Style.all().filter("id=", int(id)).get()
                    query = db.GqlQuery("SELECT * FROM Style WHERE id=:1", id)
                    style = query.get()
                    if style:
                        style.content = content
                    else:
                        style = models.Style(id=id, content=content)
                else:
                    style = models.Style(id=id, content=content)
            
            if style is not None:
                style.put()
                logging.info("put")
                logging.info(style)
                return HttpResponseRedirect("/vp/css/?action=edit&id="+str(style.id))
            else:
                return HttpResponseRedirect("/vp/css/?action=add")
        elif action=="list":
            styles = db.GqlQuery("SELECT * FROM Style ORDER BY id").fetch(10)
            logging.info("%d"%(len(styles)));
            if styles and len(styles)>0:
                body_new=u"\n<div style='width:320px;height:460px;'><div align='center'><input type='radio' name='style' id='%d' value='%d'/><label for='%d'>样式序号: <span style='color:red;font-weight:bold;'>%d</span></label></div><iframe src='/vp/css/?action=view&id=%d' style='overflow-x:hidden;overflow-y:hidden;width:340px;height:480px;border:none;'></iframe></div>\n"
                body = u""
                for style in styles:
                    body += body_new%(style.id, style.id, style.id, style.id, style.id)
                
            html = u"<html><head><style>%s</style></head><body><form>%s</form></body></html>"%(css, body)
            return HttpResponse(html)
        elif action=="view":
            id = request.GET.get("id", None)
            logging.info(id)
            if id is not None:
                #style = models.Style.all().filter("id=", int(id)).get()
                query = db.GqlQuery("SELECT * FROM Style WHERE id=:1", int(id))
                style = query.get()
                if style:
                    css = style.content
            html = "<html><head><style>%s</style></head><body>%s</body></html>"%(css, body)
            response = HttpResponse(html)
            return response
        else:
            id = request.GET.get("id", None)
            logging.info(id)
            if id is not None:
                #style = models.Style.all().filter("id=", int(id)).get()
                query = db.GqlQuery("SELECT * FROM Style WHERE id=:1", int(id))
                style = query.get()
                if style:
                    css = style.content
            
            response = HttpResponse(css)
            return response
    except:
        return HttpResponse("")

# ##########################################################################################################################
# get Post Config
def getPostConifg(request):
    show_title = request.GET.get("title", None)
    show_sender = request.GET.get("sender", None)
    show_date = request.GET.get("date", None)
    show_ip = request.GET.get("ip", None)
    show_ref = request.GET.get("ref", None)
    show_signature = request.GET.get("sign", None)
    show_attachment = request.GET.get("att", None)
    
    if show_title is not None:
        show_title = True
    else:
        show_title = False
    if show_sender is not None:
        show_sender = True
    else:
        show_sender = False
    if show_date is not None:
        show_date = True
    else:
        show_date = False
    if show_ip is not None:
        show_ip = True
    else:
        show_ip = False
    if show_ref is not None:
        show_ref = True
    else:
        show_ref = False
    if show_signature is not None:
        show_signature = True
    else:
        show_signature = False
    if show_attachment is not None:
        show_attachment = True
    else:
        show_attachment = False
    
    #config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    config = models.Configuration(showTitle=show_title, showSender=show_sender, showDate=show_date, showIP=show_ip, showRef = show_ref, showSignature = show_signature, showAttachment=show_attachment)
    config.showPost = True

    return config

# ##########################################################################################################################
# get Post Content
def getPostContent(board_id, post_id, post_type, config):
    
    post_id = smth.getPostId(board_id, post_id, post_type)
    
    post = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
    
    #logging.info("--------------------------")
    #logging.info(post)
    
    if not post:
        post_id, thread_id, post_title, pub_time, from_ip, user_name, content_text, ref, attachment_html, signature = smth.getPostContent(board_id, post_id)
        #logging.info(post_id)
        
        board_id=int(board_id)
        post_id=int(post_id)
        thread_id=int(thread_id)
        
        from_ip = unicode(from_ip, 'utf-8', 'ignore')
        author=unicode(user_name, 'utf-8', 'ignore')
        ref=unicode(ref, 'utf-8', 'ignore')
        attachment_html=unicode(attachment_html, 'utf-8', 'ignore')
        signature=unicode(signature, 'utf-8', 'ignore')
        content_text=unicode(content_text, 'utf-8', 'ignore')
        post_title = unicode(post_title, 'utf-8', 'ignore')
        
        post = models.Post(board_id=board_id, post_id=post_id, thread_id=thread_id, author=author, from_ip=from_ip, post_time=pub_time, ref=ref, attachment=attachment_html, signature=signature, content=content_text, title=post_title)
        try:
            post.put()
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
            models.cleanOldPosts()
            mail.send_mail(sender="ipsmth@googleappengine.com",
              to="Demiao Lin <ldmiao@gmail.com>",
              subject="It seems that ipsmth had a OverQuotaError",
              body='''
                Dear Demiao:
                
                Your http://ipsmth.appspot.com just had a OverQuotaError:
                --------------------------------
                '''
                + message +
                '''
                --------------------------------
                
                Please check it if you have time.
                
                From: ipsmth@googleappengine.com''')
    
    return post.post_id, post.thread_id, post.title, post.toHTMLForViewPoint(config)